package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
检查登录
 */
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将请求和响应对象转换为和HTTP协议相关的对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取会话域对象中的数据
        Object username = request.getSession().getAttribute("username");
        //判断用户名
        if (username==null||"".equals(username)){
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
            return;
        }
        //放行
        filterChain.doFilter(request,response);
    }
}
